import { Map, View } from "ol";
import { ScaleLine, defaults as defaultControls } from "ol/control.js";
import ZoomSlider from "ol/control/ZoomSlider.js";
import { fromLonLat, transform } from "ol/proj";
import { Vector as VectorLayer, Heatmap as HeatmapLayer } from "ol/layer";
import Overlay from "ol/Overlay";
import Draw from "ol/interaction/Draw";
import { getLength, getArea } from "ol/sphere";
import { unByKey } from 'ol/Observable';
import Point from "ol/geom/Point";
import VectorSource from "ol/source/Vector";
import { Modify, Select } from "ol/interaction";
import WKT from "ol/format/WKT";
import { LineString, MultiLineString, } from "ol/geom";
import { boundingExtent } from 'ol/extent';
import { transformExtent } from 'ol/proj';
import {
    Circle as CircleStyle,
    Fill,
    Stroke,
    Style,
    Text,
    Icon,
    Circle,
} from "ol/style";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { ref, watch } from "vue";
import { mainStore } from "../store";
import Feature from "ol/Feature";
import $router from "../router/index";
import axios from "axios";
const map = ref(null);
const GLZlayer5 = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        zIndex: 999,
        name: 'GLZLayer5',
        minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
        maxResolution: 50
    })
)
const GLZlayer1 = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        zIndex: 999,
        name: 'GLZLayer1',
        minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
        maxResolution: 8
    })
)
const FWQLayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        zIndex: 999,
        name: 'FWQLayer',
        minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
        maxResolution: 1000
    })
)
const SFZLayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        zIndex: 999,
        name: 'SFZLayer',
        minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
        maxResolution: 1000
    })
)
const HWLayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'HWLayer',
        zIndex: 5,
        minResolution: 0,
        maxResolution: 2700
    })
)
const ShiLayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'ShiLayer',
        zIndex: 13,
        minResolution: 100,
        maxResolution: 2700
    })
)
const XianLayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'XianLayer',
        zIndex: 12,
        minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
        maxResolution: 2700
    })
)
const extent = boundingExtent([
    [111.53366916266812, 34.43431079252504], // 最左端
    [114.28636691657437, 32.84404428026848] // 最右端
])
export function init() {
    getSetting()
    map.value = new Map({
        target: 'map',
        view: new View({
            center: fromLonLat([113.19435031501187, 33.7553879001849]),
            maxZoom: 18,
            minZoom: 7,
            zoom: 10,
            projection: "EPSG:3857",
            //1.设置缩放级别为整数
            constrainResolution: true,
            //2.关闭无级缩放地图
            smoothResolutionConstraint: true,
            extent: transformExtent(extent, 'EPSG:4326', 'EPSG:3857'),
        }),
        controls: defaultControls().extend([new ZoomSlider()]),
    })
    axios.get('./data/sys.json').then(res => {
        lyrList.value = [
            new TileLayer({
                name: "电子地图",
                visible: true,
                zIndex: 4,
                source: new XYZ({
                    url: res.data.dz,
                    // url: "http://192.168.10.9:9797/map/{z}/{x}/{y}?T=jtmap",
                    wrapX: false,
                    crossOrigin: 'anonymous'
                }),
                minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
                maxResolution: 2700
            }),
            new TileLayer({
                name: "隧道地图",
                visible: true,
                zIndex: 3,
                source: new XYZ({
                    url: res.data.wrj,
                    // url: "http://192.168.10.9:9797/map/{z}/{x}/{y}?T=jtmap",
                    wrapX: false,
                    crossOrigin: 'anonymous'
                }),
                minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
                maxResolution: 2700
            }),
            new TileLayer({
                name: "隧道地图",
                visible: true,
                zIndex: 2,
                source: new XYZ({
                    url: res.data.ygy,
                    // url: "http://192.168.10.9:9797/map/{z}/{x}/{y}?T=jtmap",
                    wrapX: false,
                    crossOrigin: 'anonymous'
                }),
                minResolution: 0, // 图层的最小分辨率，小于这个分辨率的瓦片不会被加载
                maxResolution: 2700
            }),
            new TileLayer({
                name: "卫星地图",
                visible: true,
                zIndex: 1,
                source: new XYZ({
                    url: res.data.wx,
                    // url: "http://192.168.10.9:9022/jiaotang/wx/{z}/{x}/{y}.png",
                    wrapX: false,
                    crossOrigin: 'anonymous'
                }),
            })
        ]
        lyrList.value.forEach((element) => {
            map.value.addLayer(element);
        });
    })

    let dzmap = localStorage.getItem('dzmap');
    let wxmap = localStorage.getItem('wxmap');
    if (dzmap) {
        if (dzmap == 'false') {
            setLayerVisible('电子地图', false)
        } else {
            setLayerVisible('电子地图', true)
        }
    }
    if (wxmap) {
        if (wxmap == 'false') {
            setLayerVisible('卫星地图', false)
        } else {
            setLayerVisible('卫星地图', true)
        }
    }
    VectorLayerList.value.forEach((element) => {
        map.value.addLayer(element);
    })
    map.value.addLayer(GLZlayer5.value);
    map.value.addLayer(GLZlayer1.value);
    map.value.addLayer(FWQLayer.value);
    map.value.addLayer(SFZLayer.value);
    map.value.addLayer(HWLayer.value);
    map.value.addLayer(ShiLayer.value);
    map.value.addLayer(XianLayer.value);
    reMoveRight();
    leftClickEvt();
    cursor();
}
export function unloadMap() {
    if (map.value) {
        map.value.setTarget(null);
        map.value.dispose();
        map.value = null;
    }
}
var settobj = ref({});
function getSetting() {
    axios.get('/data/sys.json').then(res => {
        settobj.value = res.data;
        console.log(settobj, 'seting');
    })
}


const lyrList = ref([


]);
export function setLayerVisible(name, show) {
    lyrList.value.forEach((item, index) => {
        if (item.values_.name == name) {
            item.setVisible(show)
        }
    })
}
const qbbsource = new VectorSource({
    features: [],
    wrapX: false
});
const VectorLayerList = ref([
    new VectorLayer({
        name: 'icon',
        source: qbbsource,
        zIndex: 1000,
        visible: true,
        minZoom: 11
    })
])
function reMoveRight() {
    map.value.getViewport().addEventListener('contextmenu', (e) => {
        e.preventDefault();
    })
}
function leftClickEvt() {

    map.value.on('click', (e) => {
        let geom = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326');
        
        if (mainStore().catchFlag) {
            mainStore().catchLon = geom[0].toFixed(7);
            mainStore().catchLat = geom[1].toFixed(7);
            mainStore().m_showGISMap=false;
            mainStore().catchFlag=false;
        } else {
            let pixel = map.value.getEventPixel(e.originalEvent);
            var feature = map.value.forEachFeatureAtPixel(pixel, function (feature) {
                return feature;
            })
            if (feature == undefined) {
                return;
            } else if (feature.values_.type == 'qbb') {
                OpenMapDlg(feature.values_.code)
            }
        }
    })
}
export function movePoint() {
    let modify = new Modify({
        source: qbbsource
    });
    map.value.addInteraction(modify);
    modify.on('modifystart', (e) => {
    });
    modify.on('modifyend', (e) => {
        let coord = e.features.item(0).getGeometry().getCoordinates();
        let geom = transform(coord, 'EPSG:3857', 'EPSG:4326');
        mainStore().catchLon = geom[0];
        mainStore().catchLat = geom[1];
        mainStore().catchFlag = false;
        mainStore().tempTitle = '修改情报板';
        $router.push({
            name: 'ledger'
        })
    })
}
function OpenMapDlg(id) {
    mainStore().MapDeviceId = id;
    setTimeout(() => {
        mainStore().MapDlg = true;
    }, 50);
}
function cursor() {
    map.value.on('pointermove', (e) => {
        let pixel = map.value.getEventPixel(e.originalEvent);
        var feature = map.value.forEachFeatureAtPixel(pixel, function (feature) {
            return feature;
        })
        if (feature == undefined) {
            map.value.getTargetElement().style.cursor = "auto"
        } else {
            map.value.getTargetElement().style.cursor = "pointer"
        }
    })
}
function getLayerByName(name) {
    let allLayers = map.value.getLayers().getArray();
    let layer = undefined;
    if (allLayers.length) {
        for (let i = 0; i < allLayers.length; i++) {
            if (allLayers[i].get('name') === name) {
                layer = allLayers[i];
                break;
            }
        }
    }
    return layer;
}

export function ClearIcon() {
    let m_layer = getLayerByName('icon');
    m_layer.getSource().clear();
}
// export function addPOINT(name, code, coordinate, imgsize, fontsize, fontcolor, onlyone, online, img) {
//     let m_layer = getLayerByName('icon');
//     if (m_layer && onlyone) {
//         m_layer.getSource().clear();
//     }
//     let obj = null;
//     if (Array.isArray(coordinate)) {
//         obj = new Feature({
//             geometry: new Point(fromLonLat(coordinate)),
//         })
//     } else {
//         let format = new WKT();
//         let geom = format.readGeometry(coordinate);
//         obj = new Feature({
//             geometry: geom,
//         });
//     }
//     obj.set('type', 'qbb');
//     obj.set('code', code);
//     obj.setStyle(
//         new Style({
//             image: new Icon({
//                 src: img,
//                 scale: 1,
//                 anchor: [0, 20],
//                 anchorXUnits: 'pixels',
//                 anchorYUnits: 'pixels'
//             }),
//             text: new Text({
//                 // text: '测\n试',
//                 text: name,
//                 font: `${fontsize}px font-size`,
//                 fill: new Fill({
//                     // 设置字体颜色
//                     color: fontcolor,
//                 }),
//                 stroke: new Stroke({
//                     color: '#000000',
//                     width: 1
//                 }),
//                 placement: 'point',
//                 textBaseline:'bottom',
//                 textAlign: 'left',
//                 offsetY: -25,
//                 offsetX: 55,
//                 padding:[5,30,5,30],

//                 backgroundFill: new Fill({
//                     width:50,
//                     color: 'rgba(0,0,0,1)'
//                     // color: 'rgba(51,51,51,.7)'
//                 }),
//             })
//         })
//     );
//     m_layer.getSource().addFeature(obj);
// }
export function addPOINT(name, code, coordinate, imgsize, fontsize, fontcolor, onlyone, online, img) {
    let m_layer = getLayerByName('icon');
    if (m_layer && onlyone) {
        m_layer.getSource().clear();
    }
    let obj = null;
    if (Array.isArray(coordinate)) {
        obj = new Feature({
            geometry: new Point(fromLonLat(coordinate)),
        })
    } else {
        let format = new WKT();
        let geom = format.readGeometry(coordinate);
        obj = new Feature({
            geometry: geom,
        });
    }
    obj.set('type', 'qbb');
    obj.set('code', code);
    obj.setStyle(
        new Style({
            image: new Icon({
                src: img,
                scale: 1,
                anchor: [12, 40],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels'
            }),
            text: new Text({
                // text: '测\n试',
                text: name,
                font: `${fontsize}px font-size`,
                fill: new Fill({
                    // 设置字体颜色
                    color: fontcolor,
                }),
                stroke: new Stroke({
                    color: '#000000',
                    width: 1
                }),
                placement: 'point',
                textAlign: 'left',
                offsetY: -28,
                offsetX: 13,
                backgroundFill: new Fill({
                    color: 'rgba(51,51,51,.7)'
                }),
            })
        })
    );
    m_layer.getSource().addFeature(obj);
}
let measureType = 'diatence'; //类型
let draw = ref(null);
let vectorLayer = ref(null);
let tipDiv = ref(null);
let pointermoveEvent = null; // 地图pointermove事件
let sketchFeature = null; // 绘制的要素
let geometryListener = null; // 要素几何change事件
let measureResult = "0"; // 测量结果
const creatDraw = (type) => {
    let maxPoints = null;
    if (measureType == "angle") maxPoints = 3;
    else maxPoints = null;
    // 矢量图层源
    let vectorSource = new VectorSource({
        wrapX: false
    });
    // 矢量图层
    vectorLayer.value = new VectorLayer({
        source: vectorSource,
        style: new Style({
            fill: new Fill({
                color: 'rgba(46, 198, 255, 0.2)'
            }),
            stroke: new Stroke({
                color: '#2ec6ff',
                width: 3
            }),
            image: new Circle({
                radius: 0,
                fill: new Fill({
                    color: '#2ec6ff'
                })
            })
        })
    });
    map.value.addLayer(vectorLayer.value);
    draw.value = new Draw({
        source: vectorSource,
        type: type,
        maxPoints: maxPoints,
        style: new Style({
            fill: new Fill({
                color: 'rgba(46, 198, 255, 0.2)'
            }),
            stroke: new Stroke({
                color: '#2ec6ff',
                lineDash: [10, 10],
                width: 3
            }),
            image: new Circle({
                radius: 0,
                fill: new Fill({
                    color: '#2ec6ff'
                })
            })
        }),
        condition: (evt) => {
            if (measureResult != "0" && !map.value.getOverlayById(measureResult) && measureType == "distence")
                creatMark(null, measureResult, measureResult).setPosition(evt.coordinate);
            return true;
        }
    });
    map.value.addInteraction(draw.value);
    /**
     * 绘制开始事件
     */
    draw.value.on("drawstart", (e) => {
        sketchFeature = e.feature;
        let proj = map.value.getView().getProjection();
        //******距离测量开始时*****//
        if (measureType == "distence") {
            creatMark(null, "起点", "start").setPosition(map.value.getCoordinateFromPixel(e.target.downPx_));
            tipDiv.value.innerHTML = "总长：0 m</br>单击确定地点，双击结束";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                measureResult = distenceFormat(getLength(evt.target, { "projection": proj, "radius": 6378137 }));
                tipDiv.value.innerHTML = "总长：" + measureResult + "</br>单击确定地点，双击结束";
            });
        }
        //******面积测量开始时*****//
        else if (measureType == "area") {
            tipDiv.value.innerHTML = "面积：0 m<sup>2</sup></br>继续单击确定地点";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                if (evt.target.getCoordinates()[0].length < 4) tipDiv.value.innerHTML = "面积：0m<sup>2</sup></br>继续单击确定地点";
                else {

                    measureResult = formatArea(getArea(evt.target, { "projection": proj, "radius": 6378137 }));
                    tipDiv.value.innerHTML = "面积：" + measureResult + "</br>单击确定地点，双击结束";
                }
            });
        }
        //******角度测量开始时*****//
        else if (measureType == "angle") {
            tipDiv.value.innerHTML = "继续单击确定顶点";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                if (evt.target.getCoordinates().length < 3) tipDiv.value.innerHTML = "继续单击确定顶点";
                else {
                    measureResult = formatAngle(evt.target);
                    tipDiv.value.innerHTML = "角度：" + measureResult + "</br>继续单击结束";
                }
            });
        }
    });

    /**
     * 绘制结束事件
     */
    draw.value.on("drawend", (e) => {
        let closeBtn = document.createElement('span');
        closeBtn.innerHTML = "×";
        closeBtn.title = "清除测量";
        closeBtn.style = `
        width: 20px;
        height:20px;
        color:#000;
        line-height: 12px;
        text-align: center;
        border-radius: 50%;
        display: inline-block;
        padding: 2px;
        color: rgb(46, 198, 255);
        border: 2px solid rgb(46, 198, 255);
        background-color: rgb(255, 255, 255);
        font-weight: 600;
        position: absolute;
        top: -36px;
        right: -17px;
        font-size: 15px;
        cursor: pointer;`;
        closeBtn.addEventListener('click', () => {
            clearMeasure();
        });
        //******距离测量结束时*****//
        if (measureType == "distence") {
            creatMark(closeBtn, null, "close1").setPosition(e.feature.getGeometry().getLastCoordinate());
            creatMark(null, "总长：" + measureResult + "", "length").setPosition(e.feature.getGeometry().getLastCoordinate());
            map.value.removeOverlay(map.value.getOverlayById(measureResult));
        }
        //******面积测量结束时*****//
        else if (measureType == "area") {
            let ft = e.feature;
            let geom = ft.getGeometry();
            let arr = geom.getCoordinates()[0];
            let codarr = [];
            codarr = arr.filter((ele, ind) => ind > 0);
            creatMark(closeBtn, null, "close2").setPosition(e.feature.getGeometry().getInteriorPoint().getCoordinates());
            creatMark(null, "总面积：" + measureResult + "", "area").setPosition(e.feature.getGeometry().getInteriorPoint().getCoordinates());
        }
        //******角度测量结束时*****//
        else if (measureType == "angle") {
            creatMark(closeBtn, null, "close3").setPosition(e.feature.getGeometry().getCoordinates()[1]);
            creatMark(null, "角度：" + measureResult + "", "angle").setPosition(e.feature.getGeometry().getCoordinates()[1]);
        }
        // 停止测量
        stopMeasure();
    });
};
// 测量
export function measure(type) {
    if (draw.value != null) return false; // 防止在绘制过程再创建测量
    measureType = type;
    if (vectorLayer.value != null) clearMeasure();
    tipDiv.value = document.createElement('div');
    tipDiv.value.innerHTML = '单击确定起点';
    tipDiv.value.className = "tipDiv.value";
    tipDiv.value.style = `
    width:auto;
    height:auto;
    color:#000;
    padding:4px;
    border:1px solid #2ec6ff;
    font-size:12px;
    background-color:#fff;
    position:relative;
    top:60%;
    left:60%;
    font-weight:600;`;

    let overlay = new Overlay({
        element: tipDiv.value,
        autoPan: false,
        positioning: "bottom-center",
        id: "tipLay",
        stopEvent: false //停止事件传播到地图
    });
    map.value.addOverlay(overlay);
    pointermoveEvent = map.value.on("pointermove", (evt) => {
        overlay.setPosition(evt.coordinate);
    });
    if (measureType == "distence" || measureType == "angle") {
        creatDraw("LineString");
    }
    else if (measureType == "area") {
        creatDraw("Polygon");
    }
}

// 创建标记
const creatMark = (markDom, txt, idstr) => {
    if (markDom == null) {
        markDom = document.createElement('div');
        markDom.innerHTML = txt;
        markDom.style = `
        width:auto;
        height:auto;
        color:#000;
        padding:4px;
        border:1px solid #2ec6ff;
        font-size:12px;
        background-color:#fff;
        position:relative;
        top:60%;
        left:60%;
        font-weight:600;`;
    }
    let overlay = new Overlay({
        element: markDom,
        autoPan: false,
        positioning: "bottom-center",
        id: idstr,
        stopEvent: false
    });
    map.value.addOverlay(overlay);
    return overlay;
};
// 格式化距离结果输出
const distenceFormat = (length) => {
    let output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; //换算成km单位
    } else {
        output = (Math.round(length * 100) / 100) + ' ' + 'm'; //m为单位
    }
    return output;//返回线的长度
};
// 格式化面积输出
const formatArea = (area) => {
    let output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'; //换算成km单位
    } else {
        output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>';//m为单位
    }
    return output; //返回多边形的面积
};
// 计算角度输出
const formatAngle = (line) => {
    var coordinates = line.getCoordinates();
    var angle = '0°';
    if (coordinates.length == 3) {
        const disa = getLength(new Feature({
            geometry: new LineString([coordinates[0], coordinates[1]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });
        const disb = getLength(new Feature({
            geometry: new LineString([coordinates[1], coordinates[2]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });
        const disc = getLength(new Feature({
            geometry: new LineString([coordinates[0], coordinates[2]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });
        var cos = (disa * disa + disb * disb - disc * disc) / (2 * disa * disb); // 计算cos值
        angle = (Math.acos(cos) * 180) / Math.PI; // 角度值
        angle = angle.toFixed(2); // 结果保留两位小数
    }
    if (isNaN(angle)) return "0°";
    else return angle + "°"; // 返回角度
};
// 停止测量
const stopMeasure = () => {
    tipDiv.value = null;
    map.value.removeInteraction(draw.value); // 移除绘制组件
    draw.value = null;
    map.value.removeOverlay(map.value.getOverlayById("tipLay")); // 移除动态提示框
};
// 清除测量
const clearMeasure = () => {
    vectorLayer.value.getSource().clear();
    map.value.getOverlays().clear();
    //移除监听事件
    unByKey(pointermoveEvent); // 清除鼠标在地图的pointermove事件
    unByKey(geometryListener); // 清除绘制图像change事件
    pointermoveEvent = null;
    geometryListener = null;
    measureResult = "0";
};
// 重置
const resetMeasure = () => {
    if (draw.value != null) stopMeasure();
    if (vectorLayer.value != null) clearMeasure();
};
export function zoomin() {
    let view = map.value.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom + 1);
}
export function zoomout() {
    let view = map.value.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom - 1);
}
export function formatPoint(data) {
    let format = data.replace("POINT(", "");
    format = format.replace(")", "");
    let lonlat = [];
    let x = format.split(" ")[0] / 20037508.34 * 180;
    let y = format.split(" ")[1] / 20037508.34 * 180;
    y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
    lonlat[0] = x;
    lonlat[1] = y;
    return lonlat;
}
export function aimto(geom) {
    map.value.getView().animate({
        center: fromLonLat(geom),
        zoom: 16,
        duration: 1000
    });
}
export function aimtocenter(geom) {
    map.value.getView().animate({
        center: fromLonLat([113.19435031501187, 33.7553879001849]),
        zoom: 10,
        duration: 1000
    });
}
export function addGlz(data) {
    let m_layer5 = getLayerByName('GLZLayer5');
    let m_layer1 = getLayerByName('GLZLayer1');
    m_layer5.getSource().clear();
    m_layer1.getSource().clear();
    let glz5list = [];
    let glz1list = [];
    data.forEach((item, index) => {
        if (item.stake % 5 == 0) {
            // let pos = formatPoint(item.geom);
            let glzfeature = new Feature({
                geometry: new Point(fromLonLat(item.geom))
            })
            glzfeature.setStyle(new Style({
                text: new Text({
                    text: 'K' + item.stake,
                    fill: new Fill({
                        color: "#ffffff",
                    }),
                    font: 12 + 'px 微软雅黑',
                    placement: 'point',
                    textAlign: 'center',
                    offsetY: -12,
                    offsetX: 0,
                }),
                image: new Icon({
                    src: "/img/zh.png",
                    scale: 1,
                }),
            }));
            glz5list.push(glzfeature);
        }
        if (item.stake % 5 != 0) {
            // let pos = formatPoint(item.geom);
            let glzfeature = new Feature({
                geometry: new Point(fromLonLat(item.geom))
            })
            glzfeature.setStyle(new Style({
                text: new Text({
                    text: 'K' + item.stake,
                    fill: new Fill({
                        color: "#ffffff",
                    }),
                    font: 12 + 'px 微软雅黑',
                    placement: 'point',
                    textAlign: 'center',
                    offsetY: -12,
                    offsetX: 0,
                }),
                image: new Icon({
                    src: "/img/zh.png",
                    scale: 1,
                }),
            }));
            glz1list.push(glzfeature);
        }
    })
    m_layer5.getSource().addFeatures(glz5list);
    m_layer1.getSource().addFeatures(glz1list);
}

export function addSFZ(data) {
    let m_layer = getLayerByName('SFZLayer');
    m_layer.getSource().clear();
    let sfzList = [];
    data.forEach((item, index) => {
        // let pos = formatPoint(item.geom);
        let sfzfeature = new Feature({
            geometry: new Point(fromLonLat(item.geom))
        })
        let length = item.name.length;
        let fontsize = 17;
        let img = "/img/sfz.png";
        if (length <= 3) {
            // fontsize = 13;
            img = "/img/sfz.png";
        } else if (length >= 4) {
            // fontsize = 12;
            img = "/img/sfz.png";
        }
        sfzfeature.setStyle(new Style({
            text: new Text({
                text: item.name,
                fill: new Fill({
                    color: "#ffffff",
                }),
                stroke: new Stroke({
                    color: "#000000",
                    width: 2,
                }),
                font: fontsize + 'px 微软雅黑',
                placement: 'point',
                textAlign: 'left',
                offsetY: -28,
                offsetX: 39,
                backgroundFill: new Fill({
                    color: 'rgba(10,175,103,.5)'
                }),
                // 
            }),
            image: new Icon({
                src: img,
                scale: 1,
                anchor: [0, 40],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels'
            }),
        }));
        sfzList.push(sfzfeature);
    })
    m_layer.getSource().addFeatures(sfzList);
}
export function addShi(data) {
    let m_layer = getLayerByName('ShiLayer');
    m_layer.getSource().clear();
    let shiList = [];
    data.forEach((item, index) => {
        let shifeature = new Feature({
            geometry: new Point(fromLonLat(item.geom))
        })
        shifeature.setStyle(new Style({
            text: new Text({
                text: item.name,
                fill: new Fill({
                    color: "#ff0000",
                }),
                stroke: new Stroke({
                    color: "#000000",
                    width: 1,
                }),
                font: '19px 微软雅黑',
                placement: 'point',
                textAlign: 'center',
                offsetY: 1,
                offsetX: 14,
            })
        }))
        shiList.push(shifeature);
    })
    m_layer.getSource().addFeatures(shiList);
}
export function addXian(data) {
    let m_layer = getLayerByName('XianLayer');
    m_layer.getSource().clear();
    let xianList = [];
    data.forEach((item, index) => {
        let xianfeature = new Feature({
            geometry: new Point(fromLonLat(item.geom))
        })
        let fontcolor = "#01a2ff"
        // if(item.name=='邓州市'){
        //     fontcolor="#ffff80"
        // }
        xianfeature.setStyle(new Style({
            text: new Text({
                text: item.name,
                fill: new Fill({
                    color: fontcolor,
                }),
                stroke: new Stroke({
                    color: "#000000",
                    width: 2,
                }),
                font: '16px 微软雅黑',
                placement: 'point',
                textAlign: 'center',
                offsetY: 1,
                offsetX: 14,
            })
        }))
        xianList.push(xianfeature);
    })
    m_layer.getSource().addFeatures(xianList);
}
// FWQLayer
export function addFWQ(data) {
    let m_layer = getLayerByName('FWQLayer');
    m_layer.getSource().clear();
    let fwqList = [];
    data.forEach((item, index) => {
        // let pos = formatPoint(item.geom);
        let fwqfeature = new Feature({
            geometry: new Point(fromLonLat(item.geom))
        })
        let length = item.name.length;
        let fontsize = 17;
        let img = "/img/fwq.png";
        if (length <= 3) {
            // fontsize = 13;
            img = "/img/fwq.png";
        } else if (length >= 4) {
            // fontsize = 12;
            img = "/img/fwq.png";
        }
        fwqfeature.setStyle(new Style({
            text: new Text({
                text: item.name, // 文本内容
                fill: new Fill({
                    color: "#ffffff",
                }),
                stroke: new Stroke({
                    color: "#000000",
                    width: 2,
                }),
                backgroundFill: new Fill({
                    color: 'rgba(18,208,8,.5)'
                }),
                font: fontsize + 'px 微软雅黑', // 字体样式
                placement: 'point', // 位置
                textAlign: 'left', // 文本对齐
                offsetY: -28, // 垂直偏移
                offsetX: 39,
            }),
            image: new Icon({
                src: img,
                scale: 1,
                anchor: [0, 40],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels'
            }),

        }));
        fwqList.push(fwqfeature);
    })
    m_layer.getSource().addFeatures(fwqList);
}
export function drawHeighWay() {
    let m_layer = getLayerByName('HWLayer');
    // m_layer.values_.visible=true;
    axios.get('./data/zs.json').then(res => {

        res.data.features.forEach((item, index) => {
            let geomarr = item.geometry.coordinates;

            // let arr=[...geomarr[1]];
            // let narrr=[];
            // arr.forEach((item,index)=>{

            //     // item = transform(item, 'EPSG:4326', 'EPSG:3857');
            //     console.log(item,'zsjson');
            //     narrr.push(transform(item, 'EPSG:4326', 'EPSG:3857'));
            // })
            // setTimeout(() => {
            //     console.log(narrr,'zsjson');
            // }, 500);

            geomarr.forEach((itm, ind) => {
                var arr_xy = "";
                if (itm != null) {
                    for (var i = 0; i < itm.length; i++) {
                        var xy = itm[i];
                        if (arr_xy == "") {
                            arr_xy = xy[0] + " " + xy[1];
                        } else {
                            arr_xy = arr_xy + "," + xy[0] + " " + xy[1];
                        }
                    }
                    var geoLine = "MultiLineString((" + arr_xy + "))";
                    let lineString = new WKT().readGeometry(geoLine, {
                        // 处理MULTILINESTRING字符串
                        dataProjection: "EPSG:3857",
                        featureProjection: "EPSG:3857",
                    });
                    const feature = new Feature(lineString);
                    const style = new Style({
                        // 设置MULTILINESTRING要素的样式
                        fill: new Fill({
                            color: "rgba(255, 0, 255, .1)",
                        }),
                        stroke: new Stroke({
                            color: "#00ff00",
                            width: 5,
                        }),

                    });
                    function getAnimation() {
                        return new Style({
                            stroke: new Stroke({
                                color: [204, 204, 255, 1],
                                width: 4,
                                lineDash: [2, 7],
                                lineDashOffset: feature.get(0)
                            })
                        })
                    }
                    function getStyle() {
                        return []
                    }
                    feature.setStyle(style);
                    m_layer.getSource().addFeature(feature);
                }
            })
        })
    })
}
